﻿using furion.blog.Domain.IRepositories;
using furion.blog.Domain.MySQL;
using furion.blog.Domain.Query.User;
using furion.blog.Domain.Shared;
using Furion.DependencyInjection;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;

namespace furion.blog.EntityFramework.Core.Repositories
{
    public class UserRepository : BaseSqlSugarRepository<User>, IUserRepository, ISingleton
    {

        public readonly ISqlSugarClient _db;

        public UserRepository(ISqlSugarClient db)
        {
            this._db = db;
        }


        /// <summary>
        /// 通过账号查找
        /// </summary>
        /// <param name="username"></param>
        /// <returns></returns>
        public async Task<User> FindByUsername(string username) {
            Expression<Func<User, bool>> exp = s => s.UserName == username;
            return await base.GetFirstAsync(exp);
        }

        /// <summary>
        /// 通过id查询
        /// </summary>
        /// <param name="userId"></param>
        /// <returns></returns>
        public async Task<User> FindByUserId(long userId) {
            return await base.GetByIdAsync(userId);
        }

        /// <summary>
        /// 更新
        /// </summary>
        /// <param name="user"></param>
        /// <returns></returns>
        public async Task Update(User user) {
           await base.UpdateAsync(user);
        }

        /// <summary>
        /// 查询第一条数据
        /// </summary>
        /// <param name="exp"></param>
        /// <returns></returns>
        public async Task<User> First(Expression<Func<User, bool>> exp) { 
            return await base.GetFirstAsync(exp);
        }


        /// <summary>
        /// 统计
        /// </summary>
        /// <param name="exp"></param>
        /// <returns></returns>
        public async Task<long> Count(Expression<Func<User, bool>> exp) {
            return await base.CountAsync(exp);
        }


        /// <summary>
        /// 新增
        /// </summary>
        /// <param name="user"></param>
        /// <returns></returns>
        public async Task Save(User user) {
            await base.InsertAsync(user);
        }


        /// <summary>
        /// 分页
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public async Task<PageVO> List(UserListQuery query) {
            try
            {
                var (strWhere, queryParams) = query.QueryParams();
                RefAsync<int> totalRecord = 0;
                string columns = string.Format(@"
t.user_id as userId,t.user_name as userName,t.real_name as realName,
t.nick_name as nickName,t.sex as `sex`,t.status as `status`,t.is_delete as isDelete,
t.created_time as createdTime,t.phone as `phone`,
d.dept_name as deptName,r.role_name as roleName,r.role_key as roleKey,t.is_super_admin as isSuperAdmin
");
                var list = await _db.SqlQueryable<object>
                    (@" select " + columns +
                    " from `user` t " +
                    " left join `dept` d on d.dept_id=t.dept_id " +
                    " left join `role` r on r.role_id = t.role_id ")
                    .Where(strWhere)
                    .AddParameters(queryParams)
                    .OrderBy(" t.createdTime desc ")
                    .ToPageListAsync(query.PageIndex, query.PageSize, totalRecord);
                return new PageVO { Records = list, Total = totalRecord };
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            return null;
        }

    }
}
